package com.ysu.yybk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysu.yybk.dto.GroupDTO;
import com.ysu.yybk.dto.GroupStudentDTO;
import com.ysu.yybk.entity.discuss.Discuss;
import com.ysu.yybk.entity.discuss.DiscussGroup;
import com.ysu.yybk.entity.discuss.DiscussGroupStudent;
import com.ysu.yybk.entity.discuss.DiscussItem;
import com.ysu.yybk.enums.ResultEnum;
import com.ysu.yybk.exception.YybkException;
import com.ysu.yybk.form.DiscussAddScoreFrom;
import com.ysu.yybk.form.DiscussForm;
import com.ysu.yybk.mapper.discuss.DiscussGroupMapper;
import com.ysu.yybk.mapper.discuss.DiscussGroupStudentMapper;
import com.ysu.yybk.mapper.discuss.DiscussItemMapper;
import com.ysu.yybk.mapper.discuss.DiscussMapper;
import com.ysu.yybk.service.DiscussTeacherService;
import com.ysu.yybk.util.DateConvertUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DiscussTeacherServiceImpl implements DiscussTeacherService {

    @Autowired
    private DiscussMapper discussMapper;

    @Autowired
    private DiscussGroupMapper groupMapper;

    @Autowired
    private DiscussGroupStudentMapper groupStudentMapper;

    @Autowired
    private DiscussItemMapper itemMapper;

    @Override
    public List<Discuss> discussList(Integer current, String courseId) {
        LambdaQueryWrapper<Discuss> discussWrapper = new LambdaQueryWrapper<>();
        discussWrapper.eq(Discuss::getCourseId, courseId).orderByDesc(Discuss::getCreateTime);
        Page<Discuss> page = new Page<>(current, 10, false);
        IPage<Discuss> discussIPage = discussMapper.selectPage(page, discussWrapper);
        return discussIPage.getRecords();
    }

    @Override
    public List<GroupDTO> groupList(Integer discussId) {
        // 判断该讨论是否存在  有点慢啊
        Discuss discuss = discussMapper.selectById(discussId);
        if (discuss == null) {
            throw new YybkException(ResultEnum.DISCUSS_NOT_EXIST);
        }
        List<GroupDTO> groupDTOList = new ArrayList<>();

        // 查询该讨论所有组
        LambdaQueryWrapper<DiscussGroup> groupWrapper = new LambdaQueryWrapper<>();
        groupWrapper.eq(DiscussGroup::getDiscussId, discussId);
        List<DiscussGroup> groupList = groupMapper.selectList(groupWrapper);
        // 查询组内学生
        for (DiscussGroup discussGroup : groupList) {
            // 获取groupId
            Integer groupId = discussGroup.getId();
            // 构造查询对象
            LambdaQueryWrapper<DiscussGroupStudent> groupStudentWrapper = new LambdaQueryWrapper<>();
            groupStudentWrapper.eq(DiscussGroupStudent::getDiscussId, discussId).eq(DiscussGroupStudent::getGroupId, groupId);
            List<DiscussGroupStudent> groupStudentList = groupStudentMapper.selectList(groupStudentWrapper);
            // 将查询结果放入list之中
            List<GroupStudentDTO> groupStudentDTOList = new ArrayList<>();
            for (DiscussGroupStudent groupStudent : groupStudentList) {
                GroupStudentDTO groupStudentDTO = new GroupStudentDTO();
                groupStudentDTO.setStudentId(groupStudent.getStudentId());
                groupStudentDTO.setStudentName(groupStudent.getStudentName());
                groupStudentDTOList.add(groupStudentDTO);
            }
            // 查询学生提交的答案
            LambdaQueryWrapper<DiscussItem> itemWrapper = new LambdaQueryWrapper<>();
            itemWrapper.eq(DiscussItem::getDiscussId, discussId).eq(DiscussItem::getGroupId, groupId);
            DiscussItem discussItem = itemMapper.selectOne(itemWrapper);

            GroupDTO groupDTO = new GroupDTO();
            if (discussItem != null) {
                BeanUtils.copyProperties(discussItem, groupDTO);
            }
            groupDTO.setGroupId(groupId);
            groupDTO.setGroupName(discussGroup.getName());
            groupDTO.setGroupStudentDTOList(groupStudentDTOList);
            groupDTOList.add(groupDTO);
        }
        return groupDTOList;
    }

    @Override
    @Transactional
    public void addDiscuss(DiscussForm discussForm) {
        // todo 验证课程和老师是否存在
        // 插入一次讨论
        Discuss discuss = new Discuss();
        BeanUtils.copyProperties(discussForm, discuss);
        // 计算分组数量
        Integer groupCountResult = 0; // 最终的组数
        Integer peopleCount = discussForm.getPeopleCount();
        Integer groupCount = discussForm.getGroupCount();
        if (groupCount != 0) {
            groupCountResult = groupCount;
        }
        if (peopleCount != 0) {
            int flag = discussForm.getStudentCount() % peopleCount;
            int flag0= discussForm.getStudentCount() / peopleCount;
            groupCountResult = flag == 0 ? flag0 : flag0 + 1;
        }
        discuss.setGroupCount(groupCountResult);
        discuss.setCreateTime(DateConvertUtil.date2Timestamp());
        int insert = discussMapper.insert(discuss);
        if (insert != 1) {
            throw new YybkException(ResultEnum.INSERT_FAIL);
        }
        Integer discussId = discuss.getId();
        // 进行分组
        int flag = discussForm.getStudentCount() % groupCountResult; // 判断是否时整组
        int num = discussForm.getStudentCount() / groupCountResult;
        for (int i = 0; i < groupCountResult; i++) {
            DiscussGroup discussGroup = new DiscussGroup();
            discussGroup.setDiscussId(discussId);
            discussGroup.setName("第" + (i +1) + "组");
            if (flag != 0) {
                discussGroup.setNum(num + 1);
                flag--;
            } else {
                discussGroup.setNum(num);
            }
            groupMapper.insert(discussGroup);
        }
        // 如果不是自由结组 将学生进行分组
        if (discussForm.getMode() == 2) {
            List<GroupStudentDTO> classStudentList = groupStudentMapper.getClassStudent(discussForm.getCourseId());

            LambdaQueryWrapper<DiscussGroup> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(DiscussGroup::getName, DiscussGroup::getNum).eq(DiscussGroup::getDiscussId, discussId);
            List<DiscussGroup> discussGroupList = groupMapper.selectList(wrapper);
            for (DiscussGroup discussGroup : discussGroupList) {
                DiscussGroupStudent discussGroupStudent = new DiscussGroupStudent();
                Integer groupId = Integer.valueOf(discussGroup.getName().replace("第", "").replace("组", ""));
                discussGroupStudent.setDiscussId(discussId);
                discussGroupStudent.setGroupId(groupId);
                for (int i = 0; i < discussGroup.getNum(); i++) {
                    int index = (int) (Math.random() * (classStudentList.size()));
                    discussGroupStudent.setStudentId(classStudentList.get(index).getStudentId());
                    discussGroupStudent.setStudentName(classStudentList.get(index).getStudentName());
                    int insertStudent = groupStudentMapper.insert(discussGroupStudent);
                    if (insertStudent != 1) {
                        throw new YybkException(ResultEnum.INSERT_FAIL);
                    }
                    classStudentList.remove(index);
                }
            }
        }
    }

    @Override
    public void addScore(DiscussAddScoreFrom from) {
        // 判断此次提交是否存在
        LambdaQueryWrapper<DiscussItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DiscussItem::getDiscussId, from.getDiscussId()).eq(DiscussItem::getGroupId, from.getGroupId());
        DiscussItem discussItem = itemMapper.selectOne(wrapper);

        int i;
        if (discussItem == null) {
            DiscussItem discussItemInsert = new DiscussItem();
            discussItemInsert.setDiscussId(from.getDiscussId());
            discussItemInsert.setGroupId(from.getGroupId());
            discussItemInsert.setStudentId("0");
            discussItemInsert.setStudentName("未提交");
            discussItemInsert.setCreateTime(DateConvertUtil.date2Timestamp());
            i = itemMapper.insert(discussItemInsert);
        } else {
            // 评分 （设计成可以多次修改，在前端控制成评分一次）
            discussItem.setScore(from.getScore());
            LambdaUpdateWrapper<DiscussItem> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(DiscussItem::getDiscussId, from.getDiscussId()).eq(DiscussItem::getGroupId, from.getGroupId());
            i = itemMapper.update(discussItem, updateWrapper);
        }

        if (i != 1) {
            throw new YybkException(ResultEnum.DISCUSS_ADD_SCORE_ERROR);
        }
    }
}
